package cn.itsource.Utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * OSS文件工具类
 */
public class fileUtilss {
    public static  String fileupdate(MultipartFile file){

         //1.拿到原始文件名
        String originalFilename = file.getOriginalFilename();
        //2.拿到文件名后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        //3.随机生成一个文件名
        String newfile = UUID.randomUUID().toString();
        //4.拼接一个新的文件名并在oss上存储
        String objectName=Constants.OBJECT_NAME+"/"+"newfile"+"."+suffix;



        // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build("HTTPS://"+ Constants.ENDPOINT, Constants.ACCESS_KEY, Constants.SECRET_KEY);

        try {
        // 创建PutObject请求。并上传文件
        ossClient.putObject(Constants.BUCKET_NAME, objectName, file.getInputStream());
            return "https://"+Constants.BUCKET_NAME+"."+Constants.ENDPOINT+"/"+Constants.OBJECT_NAME+"/"+newfile+"."+suffix;

    } catch (
    OSSException oe) {

    } catch (Exception e){
           e.printStackTrace();

        }
            finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
        return  null;
    }
}
